<template>
  <div class="article-list">
    <van-pull-refresh :success-text="state.refreshSuccessText" success-duration="1500" v-model="isRefreshLoading" @refresh="onRefresh">
      <van-list
        v-model:loading="state.loading"
        :finished="state.finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
      <article-item @click="loadDetail(article.art_id)" @update-active="active = $event"  v-for="(article) in state.articles" :article="article" :key="article.art_id" />
        <!-- <van-cell v-for="(article,index) in state.articles" :key="index" :title="article.title" /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script lang="ts">
import { ref, reactive, defineComponent, isRef, inject } from 'vue'
import { getArticles } from 'api/article'
import { useRouter } from 'vue-router'
import ArticleItem from 'components/article_item/index.vue'

export default defineComponent({
  props:{
    channel:{
      type:Object,
      required:true
    },
    active:{
      type:Number,
      required:true
    }
  },
  components:{
    ArticleItem
  },
    setup(props){
        name:"ArticleList"

        const router = useRouter()

        const state = reactive<any>({
          articles:[],
          loading:false,
          finished:false,
          timestamp:null,
          refreshSuccessText:""
        })

        
        const isRefreshLoading = ref<boolean>(false)

        const onLoad = async () => {
            let { data } = await getArticles({
              channel_id: props.channel.id,
              timestamp:state.timestamp || Date.now(),
              with_top:1,
            })


            const {  results } = data.data

            state.articles.push(...results)

            state.loading = false

            if(results.length) {
              state.timestamp = data.data.pre_timestamp
            } else {
              state.finished = true
            }
        }

        const onRefresh = async () => {

            const { data } = await getArticles({
              channel_id:props.channel.id,
              timestamp:Date.now(),
              with_top:1,
            })

            const { results } = data.data

            state.articles.unshift(...results)

            isRefreshLoading.value = false

            state.refreshSuccessText = `更新了${results.length}条数据`
        }

        const loadDetail = (id:number) => {
          console.log(id)
          router.push({name:"Details",params:{article_id:id}})
        }

        return {
          state,
          onLoad,
          onRefresh,
          loadDetail,
          isRefreshLoading
        }
    }
})

</script>

<style lang="scss" scoped>
  .article-list {
    position: fixed;
    overflow-y: auto;
    // position:fixed;
    top:90px;
    left: 0;
    right: 0;
    bottom:50px;
    // // margin: 90px 0 50px 0;
    // // z-index:999;
    // overflow-y: auto;
  }
</style>